<template>

  <el-form class="login_form">
    <el-input class="login_input login_item" v-model="form.account" placeholder="请输入用户名" clearable />
    <el-input class="login_input login_item" v-model="form.password" placeholder="请输入密码" show-password />
    <div class="login_img_box">
      <el-input class="login_input login_item" v-model="form.code" placeholder="请输入验证码" clearable />
      <img @click="getImgBase64" class="login_img" :src="imgBase64" alt="验证码">
    </div>
    <el-button @click="userLogin" class="login_button login_item" type="primary">登录</el-button>
    <el-button @click="userRegistry" class="login_button login_item" type="success">注册</el-button>
  </el-form>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from "vue-router";
import axios from "axios";
import {LOGIN_CAPTCHA_API, LOGIN_API, INFO_API} from "../../api/login";
import {postRequest} from "../../util/requestUtil";
import {useUserInfoStore} from "../../store/UserInfoStore";

const form = ref({
  account: '',
  password: '',
  code: '',
});

const router = useRouter();

let imgBase64 = ref('');
function getImgBase64(){
  axios.get(LOGIN_CAPTCHA_API).then((response)=>{
    imgBase64.value = response.data;
  }).catch((e)=>{
    console.log(e);
  });
}

const userInfoStore = useUserInfoStore();

function userLogin(){
  const requestData = new URLSearchParams();
  requestData.append('account', form.value.account);
  requestData.append('password', form.value.password);
  requestData.append('code', form.value.code);

  postRequest(LOGIN_API, requestData, ()=>{
    router.push("/");
    postRequest(INFO_API, {},
        (data)=>{userInfoStore.setUserInfo(data.info);},
        null, null, false)}, ()=>{getImgBase64();});
}

function userRegistry(){
  router.push("/registry");
}

onMounted(() => {
  getImgBase64();
});

</script>

<style scoped>
@import "../../assets/css/login/login_view.css";

</style>